package per.hnvcam.util.console;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * A buffered memory output stream.
 * @author Cam Hoang
 *
 */
public class ConsoleOutputStream extends OutputStream {
   private ConcurrentLinkedQueue<Character> buffer;

   public ConsoleOutputStream() {
      buffer = new ConcurrentLinkedQueue<Character>();
   }

   @Override
   public void write(int b) throws IOException {
      buffer.add((char) b);
   }

   public boolean isAvailable() {
      return !buffer.isEmpty();
   }

   public String readLine() {
      StringBuffer line = new StringBuffer();
      boolean endLine = false;
      while (!buffer.isEmpty() && !endLine) {
         Character nextChar = buffer.poll();
         if (nextChar != null && (nextChar.equals(Constants.CARRIAGE_RETURN) || nextChar.equals(Constants.LINE_FEED))) {
            endLine = true;
            Character next2Char = buffer.peek();
            if (next2Char != null && ((next2Char.equals(Constants.LINE_FEED) && nextChar.equals(Constants.CARRIAGE_RETURN))
                  || (next2Char.equals(Constants.CARRIAGE_RETURN) && nextChar.equals(Constants.LINE_FEED)))) {
               buffer.poll();
            }
         } else {
            if (nextChar != null) {
               line.append(nextChar);
            }
         }
      }
      return line.toString();
   }
}
